package cn.meye11.crm.service;

import cn.meye11.crm.common.RestResponse;
import cn.meye11.crm.common.StringUtils;
import cn.meye11.crm.domain.entity.UserEntity;
import cn.meye11.crm.domain.model.User;
import cn.meye11.crm.domain.query.UserQuery;
import cn.meye11.crm.mapper.UserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import lombok.SneakyThrows;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (User)表服务实现类
 * 默认CRUD操作
 *
 * @author makejava
 * @since 2023-11-16 14:48:00
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class UserService {

    private final UserMapper userMapper;
    private final ObjectMapper objectMapper;

    private final ApplicationEventPublisher applicationEventPublisher;

    // 代码写到此区域
    public User checkLogin(String name, String password) {
        UserQuery query = UserQuery.builder().name(name).password(password).build();
        UserEntity users = userMapper.list(query).stream().findFirst().orElse(null);
        if (ObjectUtils.isEmpty(users)) {
            return null;
        }
        return new User(users);
    }

    /************************************* 请在上方编写新代码 **************************************/
    // 此区域为自动生成的通用代码 尽量不直接修改
    @Transactional(rollbackFor = Exception.class)
    public Long save(User model) {
        if (StringUtils.isBlank(model.getCreatedBy())) {
            throw new RuntimeException("创建人不能为空");
        }
        if (model.getId() != null) {
            throw new RuntimeException("主键id不可自定义");
        }
        if (model.getVersion() != null) {
            throw new RuntimeException("数据版本号不可自定义");
        }
        if (model.getTime() != null) {
            throw new RuntimeException("数据创建时间不可自定义");
        }
        if (model.getLast() != null) {
            throw new RuntimeException("数据修改时间不可自定义");
        }

        UserEntity entity = new UserEntity(model);

        userMapper.insertSelective(entity);

        return entity.getId();
    }

    public void remove(User model) {

        if (model.getId() == null) {
            throw new RuntimeException("ID不能为空");
        }

        if (StringUtils.isBlank(model.getModifiedBy())) {
            throw new RuntimeException("修改人不能为空");
        }

        UserEntity entity = userMapper.selectByPrimaryKey(model.getId());
        if (entity == null) {
            throw new RuntimeException("ID:" + model.getId() + "不存在");
        }
        userMapper.deleteByPrimaryKey(model.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(User model) {

        if (model.getId() == null) {
            throw new RuntimeException("ID不能为空");
        }

        if (StringUtils.isBlank(model.getModifiedBy())) {
            throw new RuntimeException("修改人不能为空");
        }

        UserEntity entity = userMapper.selectByPrimaryKey(model.getId());
        if (entity == null) {
            throw new RuntimeException("ID:" + model.getId() + "不存在");
        }

        UserEntity save = new UserEntity(model);
        save.setLast(LocalDateTime.now());
        save.setTime(entity.getTime());
        userMapper.updateByPrimaryKey(save);
    }

    public User get(Integer id) {
        UserEntity entity = userMapper.selectByPrimaryKey(id);
        return entity == null ? null : new User(entity);
    }

    public Long count(UserQuery query) {
        return userMapper.count(query);
    }

    public RestResponse<List<User>> list(UserQuery query) {
        // 单次查不得大于32767条数据，否则需要分页
        query.setLimit((int) Short.MAX_VALUE);
        return page(query);
    }

    public RestResponse<List<User>> page(UserQuery query) {
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<UserEntity> list = userMapper.list(query);
        PageInfo<UserEntity> count = new PageInfo<>(list);
        List<User> collect = list.stream().map(User::new).collect(Collectors.toList());
        return RestResponse.success(count.getTotal(), collect);
    }
}
